class SettingsController < ApplicationController
  # use the same layout settings.
  layout "settings"
  # apply filter for user only access.
  before_filter :authorize
  
  # get variables to pass to index page.
  
  def index
    @user = get_user
    @page_title = "#{@user.display_name}'s Personal Settings_Microblog"
  end
  
  def update
    @user = get_user
    unless params[:user][:nick_name].index(/\w\s\w/).nil? && update_basic_info(params[:user])
      flash[:notice] = "Some information was in wrong format, double check before you submit."
    else
      flash[:notice] = "Personal Settings are successfully updated!"
    end
    @page_title = "#{@user.display_name}'s Personal Settings_Microblog"
    render(:action => "index")
  end
  
  def privacy
    @user = get_user
    @page_title = "#{@user.display_name}'s Privacy Settings_Microblog"
  end
  
  def update_privacy
    @user = get_user
    # deal with password change
    if params[:old_password] == "" or params[:new_password] == "" or params[:new_password_confirm] == ""
      # If any field left blank, just ignore the password change.
    elsif User.encrypted_password(params[:old_password]) != @user.hashed_password
      flash[:notice] = "Old password wrong. Please try again."
    elsif (params[:new_password] != params[:new_password_confirm])
      flash[:notice] = "New password and Repeated password don't match."
    else
      unless @user.update_attribute("hashed_password",User.encrypted_password(params[:new_password]))
        flash[:notice] = "Password failed to save. Please try again later."
      else
        flash[:notice] = "Privacy Settings are successfully updated!"
      end
    end
    
    # OK, the password form and the privacy form should split later.
    # Right now, just leave it there. :P 
    
    if params[:privacy].nil?
      unless @user.update_attribute("privacy","F")
        flash[:notice] = "Something unexpected happened. Please try again."
      else
        flash[:notice] = "Privacy Settings are successfully updated!"
      end
    elsif params[:privacy] = "on"
      unless @user.update_attribute("privacy","T")
        flash[:notice] = "Something unexpected happened. Please try again."
      else
        flash[:notice] = "Privacy Settings are successfully updated!"
      end
    else
      # do nothing
    end
    @page_title = "#{@user.display_name}'s Privacy Settings_Microblog"
    render(:action => "privacy")
  end

  private
  
  def get_user
    users = User.find(:all, :conditions => ["name='#{session[:user_name]}'"])
    users[0]
  end
  
  def update_basic_info(info)
    info.each do |k, v|
      @user.update_attribute(k,v)
    end
  end

end
